﻿using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace ZhuXingFamilys.AuditIndicators.utils
{
    /// <summary>
    /// 检查链接中的模型，将标高类型修改为测量点
    /// </summary>
    public class CheckLinkInstance : IExternalEventHandler
    {
        public void Execute(UIApplication app)
        {
            var doc = app.ActiveUIDocument.Document;
            var collector = new FilteredElementCollector(doc);
            collector.OfClass(typeof(RevitLinkInstance));
            foreach (RevitLinkInstance linkedInstance in collector.ToElements())
            {
                ElementId typeId = linkedInstance.GetTypeId();
                RevitLinkType linkType = doc.GetElement(typeId) as RevitLinkType;
                if (linkType.GetLinkedFileStatus() != LinkedFileStatus.Loaded) continue;

                Document linkDoc = linkedInstance.GetLinkDocument();
                string linkDocFullName = linkDoc.PathName;
                collector = new FilteredElementCollector(linkDoc);
                collector.OfCategory(BuiltInCategory.OST_Levels).OfClass(typeof(LevelType));
                LevelType targetLevel = collector.ToElements()[0] as LevelType;

                var BASE_TYPE = targetLevel.get_Parameter(BuiltInParameter.LEVEL_RELATIVE_BASE_TYPE);
                if (BASE_TYPE != null && BASE_TYPE.AsInteger() == 0)
                {
                    // 开始事务前需要先卸载 重新加载
                    linkType.Unload(new Callback());
                    Document backGroundDoc = doc.Application.OpenDocumentFile(linkDocFullName);
                    using (Transaction trans = new Transaction(backGroundDoc))
                    {
                        collector = new FilteredElementCollector(backGroundDoc);
                        collector.OfCategory(BuiltInCategory.OST_Levels).OfClass(typeof(LevelType));
                        LevelType LevelType = collector.ToElements()[0] as LevelType;
                        var BASE_TYPE1 = LevelType.get_Parameter(BuiltInParameter.LEVEL_RELATIVE_BASE_TYPE);
                        trans.Start("change the Parameter");
                        BASE_TYPE1.Set(1);//0:项目基点，1：测量点
                        trans.Commit();
                    }
                    backGroundDoc.Save();
                    backGroundDoc.Close(false);
                    linkType.Load();
                }
            }
            RealAndModel.LinkInstanceChecked = true;
        }

        public string GetName()
        {
            return "CheckLinkInstance";
        }
    }
}
